package com.yaolong.api.modules.gen.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author yaolong
 * @version V1.0.0
 * @program EasyCode
 * @description 模板工具
 * @create 2022-12-29 21:47
 **/
public class TemplateUtil {

    /**
     * <p>
     * ${变量}  解析
     * </p>
     *
     * @param template
     * @param data
     * @return java.lang.String
     * @version 1.0.0 <br>
     * @date 2022/12/30 12:52 <br>
     * @author yaolonga <br>
     */
    public static String parse(String template, Map<String, String> data) {

        String pattern = "\\$\\{(.+?)\\}";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(template);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            String key = m.group(1);
            String value = data.get(key);
            m.appendReplacement(sb, value == null ? "" : value);
        }
        m.appendTail(sb);
        return sb.toString();
    }


    public static String capitalFirst(String name) {
        return StringUtils.isNotBlank(name) ? name.substring(0, 1).toUpperCase() + name.substring(1) : "";
    }

    public static String lowercaseFirst(String name) {
        return StringUtils.isNotBlank(name) ? name.substring(0, 1).toLowerCase() + name.substring(1) : "";
    }

    public static void main(String[] args) {
        Map<String, String> data = new HashMap<>();
        data.put("name", "zhangs");
        data.put("code", "2222");
        String content = "恭喜${name}报名成功，请凭报名编号${code}到现场参加活动";

        System.out.println(TemplateUtil.parse(content, data));

    }
}
